import React from 'react'
import { Table } from 'antd'
import TaskAssignmentsTag from './task-assignments-tag'
import _ from 'lodash'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../../../../../constant/lang-util'

export default class ProgramTasksStatusBox extends React.Component {
  state = {
    taskTitle: ''
  }

  uniqByAssTag = groupByTaskAssignmentsTag => {
    return _.uniqBy(groupByTaskAssignmentsTag[Object.keys(groupByTaskAssignmentsTag)[0]], item => item.assTag)
      .filter(item => !!item.assTag)
      .map(item => item.assTag)
  }
  getColumns = groupByTaskAssignmentsTag => {
    let uniqByAssTags = this.uniqByAssTag(groupByTaskAssignmentsTag)

    const columns = [{
      title: <FormattedMessage id='任务卡'/>,
      dataIndex: 'taskTitle',
      width: 80,
      render: taskTitle => {
        return <a onClick={()=>this.setState({taskTitle})}>{taskTitle}</a>
      }
    }]
    uniqByAssTags.forEach(item => columns.push({
      title: <font color={item.split('|')[1]}>{item.split('|')[0]}</font>,
      dataIndex: item,
      width: 100,
      render: (text) => {
        return <font color={item.split('|')[1]}>{text}</font>
      }
    }))
    return columns
  }

  getData = groupByTaskAssignmentsTag => {
    let result = []
    let uniqByAssTags = this.uniqByAssTag(groupByTaskAssignmentsTag)
    const tasksTitle = Object.keys(groupByTaskAssignmentsTag)
    tasksTitle.forEach(taskTitle => {
      const currentAssignmentTagsStatus = groupByTaskAssignmentsTag[taskTitle]
      let temp = {taskTitle}
      uniqByAssTags.forEach(assTag => {
        const assTagCount = currentAssignmentTagsStatus.filter(item => item.assTag === assTag)
          .reduce((value, current) => {
            value += current.assTagCount ? current.assTagCount : 0
            return value
          }, 0)
        temp[assTag] = assTagCount
      })
      result.push(temp)
    })
    return result
  }
  filter = () => {
    const {programStudentAssignmentsTag} = this.props
    const {taskTitle} = this.state
    return programStudentAssignmentsTag.filter(item => item.taskTitle === taskTitle)
  }
  render () {
    const {programStudentAssignmentsTag} = this.props
    const {taskTitle} = this.state

    let groupByTaskAssignmentsTag = _.groupBy(programStudentAssignmentsTag, item => item.taskTitle)
    const columns = this.getColumns(groupByTaskAssignmentsTag)
    const data = this.getData(groupByTaskAssignmentsTag)

    return taskTitle
      ? <div>
        <a href='javascript:(0)' onClick={()=>this.setState({taskTitle:''})}>
          {convertContent('返回')} | {taskTitle}
        </a>
        <TaskAssignmentsTag
          taskAssignmentsTag={this.filter()}
        />
      </div>
      : <Table columns={columns}
               dataSource={data}
               pagination={false}
               bordered
               size='small'
      />
  }
}
